﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_SpecialUpdForm
 * 类型：       控制层
 * 功能说明：   生活管家-特殊任务登记页面
 * 作者：       章 昕
 * 创建日期：   2007/11/21
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using log4net;
using Shpm.App.Input.Bean;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.System;
using Shpm.App.Commons.Utils;
using Shpm.App.Master.Dao;
using Shpm.App.Master.Bean;
using Shpm.App.Common.Bean;

public partial class App_Input_SpecialUpdForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_SpecialUpdForm));


    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        txtMemberId.Attributes.Add("onblur", "showMemberName(this.id,'" + txtMemberName.ClientID + "');");
        txtMemberName.Attributes.Add("onfocus", "document.getElementById('" + txtMemberId.ClientID + "').focus();");
        txtEmpId.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtEmpName.ClientID + "');");
        txtEmpName.Attributes.Add("onfocus", "document.getElementById('" + txtEmpId.ClientID + "').focus();");

        if (!Page.IsPostBack)
        {
            // 保存接收的参数
            ViewState["BEGIN_DATE"] = Convert.ToString(Context.Items["BEGIN_DATE"]);
            ViewState["END_DATE"] = Convert.ToString(Context.Items["END_DATE"]);
            ViewState["EMPLOYEE_ID"] = Convert.ToString(Context.Items["EMPLOYEE_ID"]);
            ViewState["SEARCH_FLG"] = Convert.ToString(Context.Items["SEARCH_FLG"]);

            if (Context.Items.Contains("ParamPageIndex"))
            {
                ViewState["ParamPageIndex"] = Context.Items["ParamPageIndex"];
            }

            // 特殊任务编号
            ViewState["SPECIAL_ID"] = Convert.ToString(Context.Items["SPECIAL_ID"]);
            //ViewState["SPECIAL_ID"] = "";

            //SpecialWorkBean bean = (SpecialWorkBean)Context.Items["bean"];
            //if (bean != null)
            //{
            //    ViewState["SPECIAL_ID"] = Convert.ToString(bean.SpecialId);
            //}
            //ViewState["bean"] = bean;

            // 初始化控件
            initPageControls();

            // get data
            bindSelectData(Convert.ToString(ViewState["SPECIAL_ID"]));
        }
    }


    // 登记按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            // page 
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtSpecialDate.Text, new ComMessage("E0094", "任务日期")));
            vd.CheckItems.Add(new CheckRequired(txtEmpId.Text, new ComMessage("E0094", "任务责任人")));
            vd.CheckItems.Add(new CheckRequired(lstSpecialType.SelectedValue, new ComMessage("E0094", "任务类型")));
            vd.CheckItems.Add(new CheckRequired(lstChamberlaineType.SelectedValue, new ComMessage("E0094", "管家类型")));
            vd.CheckItems.Add(new CheckRequired(txtContent.Text, new ComMessage("E0094", "任务内容")));
            vd.CheckItems.Add(new CheckDate(txtSpecialDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "任务日期")));
            //if (!string.IsNullOrEmpty(txtBeginTime.Text))
            //{ vd.CheckItems.Add(new CheckMatches(txtBeginTime.Text, Constants.CHECK_REGEX_TIME_HOURMINUTE, new ComMessage("E0034", "任务时间（开始）"))); }
            //if (!string.IsNullOrEmpty(txtEndTime.Text))
            //{ vd.CheckItems.Add(new CheckMatches(txtEndTime.Text, Constants.CHECK_REGEX_TIME_HOURMINUTE, new ComMessage("E0034", "任务时间（结束）"))); }
            vd.CheckItems.Add(new CheckDouble(txtMoney.Text, 7, 2, new ComMessage("E0064", new string[] { "金额", "7", "2" })));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            if (string.IsNullOrEmpty(txtRoomId.Text) && string.IsNullOrEmpty(txtMemberId.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    string.Format(HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0906").ToString(), "房间编号", "服务会员");
                return;
            }

            // employee exist
            if (!checkExistPerson(txtEmpId.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "任务责任人");
                return;
            }
            // member exist
            if (!string.IsNullOrEmpty(txtMemberId.Text) && !checkExistMember(txtMemberId.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "服务会员");
                return;
            }
            // room exist
            if (!string.IsNullOrEmpty(txtRoomId.Text) && !checkExistApartment(txtRoomId.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "房间编号");
                return;
            }

            ViewState["SPECIAL_ID"] = insertUpdate(Convert.ToString(ViewState["SPECIAL_ID"]));
            bindSelectData(Convert.ToString(ViewState["SPECIAL_ID"]));
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 插入 更新 数据 
    private string insertUpdate(string specialId)
    {

        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;

        SpecialWorkDao dao = new SpecialWorkDao();
        SpecialWorkBean bean = new SpecialWorkBean();
        if (!string.IsNullOrEmpty(specialId))
        {
            bean.SpecialId = Convert.ToInt32(specialId);
            bean = dao.FindSpecialWork(bean);
            if (bean != null)
            {
                // update
                bean.EmployeeId = txtEmpId.Text;
                if (!string.IsNullOrEmpty(txtSpecialDate.Text))
                { bean.SpecialDate = DateUtils.convertToDate(txtSpecialDate.Text); }
                //bean.BeginTime = txtBeginTime.Text;
                //bean.EndTime = txtEndTime.Text;
                bean.ApartmentNo = txtRoomId.Text;
                bean.MemberNo = txtMemberId.Text;
                bean.ChamberlaineType = lstChamberlaineType.SelectedValue;
                bean.SpecialType = lstSpecialType.SelectedValue;
                if (!string.IsNullOrEmpty(txtMoney.Text))
                { bean.Amount = Convert.ToDecimal(txtMoney.Text); }
                bean.InvoiceFlg = ckbInvoice.Checked;
                bean.SpecialDelivery = txtAddress.Text;
                bean.SpecialContent = txtContent.Text;
                bean.FromEmployeeId = emplyId;
                //bean.SpecialMemo = txtMemo.Text;                

                bean.UserId = loginId;
                dao.Update(bean);
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
                return Convert.ToString(bean.SpecialId);
            }
        }

        // insert
        SpecialWorkBean beanNew = new SpecialWorkBean();
        beanNew.EmployeeId = txtEmpId.Text;
        if (!string.IsNullOrEmpty(txtSpecialDate.Text))
        { beanNew.SpecialDate = DateUtils.convertToDate(txtSpecialDate.Text); }
        //beanNew.BeginTime = txtBeginTime.Text;
        //beanNew.EndTime = txtEndTime.Text;
        beanNew.ApartmentNo = txtRoomId.Text;
        beanNew.MemberNo = txtMemberId.Text;
        beanNew.ChamberlaineType = lstChamberlaineType.SelectedValue;
        beanNew.SpecialType = lstSpecialType.SelectedValue;
        if (!string.IsNullOrEmpty(txtMoney.Text))
        { beanNew.Amount = Convert.ToDecimal(txtMoney.Text); }
        beanNew.InvoiceFlg = ckbInvoice.Checked;
        beanNew.SpecialDelivery = txtAddress.Text;
        beanNew.SpecialContent = txtContent.Text;
        //beanNew.SpecialMemo = txtMemo.Text;
        beanNew.FromEmployeeId = emplyId;
        beanNew.CompleteFlg = false;
        beanNew.PayFlg = false;
        beanNew.ReceivableFlg = false;

        beanNew.UserId = loginId;
        beanNew = dao.Insert(beanNew);
        if (beanNew == null)
        { return string.Empty; }

        ((Design_MasterPage)this.Master).InfoMessage =
            HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0001").ToString();

        // send message to work employee
        MessageBean beanMsg = new MessageBean();
        beanMsg.Subject = "特殊任务--" + DateTime.Now.ToString();
        beanMsg.Message = beanNew.SpecialContent;
        beanMsg.MessageType = 3;
        beanMsg.SendDate = DateTime.Now;
        beanMsg.ReplyFlag = false;
        beanMsg.ReaderHistoryFlag = false;
        beanMsg.ImportantFlag = false;
        beanMsg.EmployeeId = emplyId;
        beanMsg.UserId = loginId;
        string toEmployeeId = beanNew.EmployeeId;
        CommonSendMessageUtils sendMsg = new CommonSendMessageUtils(beanMsg, toEmployeeId);
        sendMsg.SendMessage();

        return Convert.ToString(beanNew.SpecialId);

    }

    // 删除按钮
    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(Convert.ToString(ViewState["SPECIAL_ID"])))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "特殊任务");
                return;
            }

            SpecialWorkDao dao = new SpecialWorkDao();
            SpecialWorkBean bean = new SpecialWorkBean();

            bean.SpecialId = Convert.ToInt32(ViewState["SPECIAL_ID"]);
            bean = dao.FindSpecialWork(bean);
            if (bean == null)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "特殊任务");
                return;
            }

            int delCnt = dao.Delete(bean);
            // clear form
            bindSelectData("");
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0003").ToString();

        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {

        // 传递接收的参数
        Context.Items["BEGIN_DATE"] = Convert.ToString(ViewState["BEGIN_DATE"]);
        Context.Items["END_DATE"] = Convert.ToString(ViewState["END_DATE"]);
        Context.Items["EMPLOYEE_ID"] = Convert.ToString(ViewState["EMPLOYEE_ID"]);
        Context.Items["SEARCH_FLG"] = Convert.ToString(ViewState["SEARCH_FLG"]);
        Context.Items["ParamPageIndex"] = Convert.ToString(ViewState["ParamPageIndex"]);

        Context.Items["bean"] = ViewState["bean"];
        string url = "~/App/Input/SpecialSrhForm.aspx";
        ControllerUtils.Transfer(Context, url, true);

    }

    // bind data to controls
    private void bindSelectData(string specialId)
    {
        lblSpecialId.Text = string.Empty;
        btnDel.Enabled = true;
        if (string.IsNullOrEmpty(Convert.ToString(specialId)))
        {
            // 新建　特殊任务
            ViewState["SPECIAL_ID"] = "";
            btnDel.Enabled = false;
            resetFormControls();
            return;
        }

        // 读取 特殊任务数据
        SpecialWorkDao dao = new SpecialWorkDao();
        SpecialWorkBean bean = new SpecialWorkBean();
        bean.SpecialId = Convert.ToInt32(specialId);
        bean = dao.FindSpecialWork(bean);
        if (bean == null)
        {
            ViewState["SPECIAL_ID"] = "";
            btnDel.Enabled = false;
            resetFormControls();
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "特殊任务");
            return;
        }

        // 编辑 特殊任务
        // set data to page
        lblSpecialId.Text = Convert.ToString(bean.SpecialId.Value);
        txtContent.Text = bean.SpecialContent;
        lstChamberlaineType.SelectedValue = bean.ChamberlaineType;
        lstSpecialType.SelectedValue = bean.SpecialType;
        //txtBeginTime.Text = bean.BeginTime;
        //txtEndTime.Text = bean.EndTime;
        txtAddress.Text = bean.SpecialDelivery;
        txtMemo.Text = bean.SpecialMemo;
        txtRoomId.Text = bean.ApartmentNo;
        txtMemberId.Text = bean.MemberNo;
        ComMemberBean beanMem = new ComMemberBean();
        beanMem.MemberNo = bean.MemberNo;
        beanMem = dao.GetMember(beanMem);
        txtMemberName.Text = (beanMem == null) ? "" : beanMem.NameC;
        txtEmpId.Text = bean.EmployeeId;
        PersonEmployeeBean beanEmp = new PersonEmployeeBean();
        beanEmp.EmployeeId = bean.EmployeeId;
        beanEmp = dao.GetEmployee(beanEmp);
        txtEmpName.Text = (beanEmp == null) ? "" : beanEmp.EmployeeName;
        if (bean.SpecialDate.HasValue)
        { txtSpecialDate.Text = DateUtils.convertToString(bean.SpecialDate.Value); }
        if (bean.Amount.HasValue)
        { txtMoney.Text = string.Format("{0:N}", bean.Amount.Value); }
        if (bean.InvoiceFlg.HasValue)
        { ckbInvoice.Checked = bean.InvoiceFlg.Value; }

        if (bean.CompleteFlg.HasValue
            && bean.CompleteFlg.Value
            && getJobLevel() < 1)
        {
            btnOk.Enabled = false;
            btnDel.Enabled = false;
        }

    }

    // reset controls to page
    private void resetFormControls()
    {
        lblSpecialId.Text = string.Empty;
        txtSpecialDate.Text = string.Empty;
        //txtBeginTime.Text = string.Empty;
        //txtEndTime.Text = string.Empty;
        txtMemberId.Text = string.Empty;
        txtMemberName.Text = string.Empty;
        txtEmpId.Text = string.Empty;
        txtEmpName.Text = string.Empty;
        txtRoomId.Text = string.Empty;
        txtMoney.Text = string.Empty;
        txtAddress.Text = string.Empty;
        txtContent.Text = string.Empty;
        txtMemo.Text = string.Empty;
        ckbInvoice.Checked = false;
        if (lstChamberlaineType.Items.Count > 0)
        { lstChamberlaineType.SelectedIndex = 0; }
        if (lstSpecialType.Items.Count > 0)
        { lstSpecialType.SelectedIndex = 0; }
        if (getJobLevel() < 1)
        {
            btnOk.Enabled = false;
            btnDel.Enabled = false;
        }
    }

    // check person exist
    private Boolean checkExistPerson(string empId)
    {
        SpecialWorkDao dao = new SpecialWorkDao();
        PersonEmployeeBean beanME = new PersonEmployeeBean();
        beanME.EmployeeId = empId;
        if (dao.GetEmployee(beanME) == null)
        { return false; }

        return true;
    }

    private Boolean checkExistMember(string memId)
    {
        SpecialWorkDao dao = new SpecialWorkDao();
        ComMemberBean bean = new ComMemberBean();
        bean.MemberNo = memId;
        if (dao.GetMember(bean) == null)
        { return false; }

        return true;
    }

    private Boolean checkExistApartment(string apartId)
    {
        SpecialWorkDao dao = new SpecialWorkDao();
        MstApartmentBean bean = new MstApartmentBean();
        bean.ApartmentNo = apartId;
        if (dao.GetApartment(bean) == null)
        { return false; }

        return true;
    }

    private int getJobLevel()
    {
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        PersonEmployeeBean beanEmp = new PersonEmployeeBean();
        SpecialWorkDao dao = new SpecialWorkDao();
        beanEmp.EmployeeId = emplyId;
        beanEmp = dao.GetEmployeeJob(beanEmp);
        if (beanEmp == null || string.IsNullOrEmpty(beanEmp.JobLimit))
        { return 0; }
        return Convert.ToInt32(beanEmp.JobLimit);//beanEmp.JobLimit.Value; 
    }


    // bind common catalog data 
    private void initPageControls()
    {
        SpecialWorkDao dao = new SpecialWorkDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 任务类型
        log.Fatal("\n ***** get 任务类型 catalog *****");
        beanComDict.Catalog = "T_SPECIAL.SPECIAL_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstSpecialType.Items.Clear();
        bindDataToListControl("lstSpecialType", lstCat);

        // 管家类型
        log.Fatal("\n ***** get 管家类型 catalog *****");
        beanComDict.Catalog = "T_SPECIAL.CHAMBERLAINE_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstChamberlaineType.Items.Clear();
        bindDataToListControl("lstChamberlaineType", lstCat);

    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }

}
